package com.chookss.tools.filePicker.activity;


import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tools.Utils;
import com.chookss.tools.filePicker.BaseFileFragment;
import com.chookss.tools.filePicker.SelectOptions;
import com.chookss.tools.filePicker.loader.EssMimeTypeCollection;
import com.chookss.tools.filePicker.model.EssFile;
import com.chookss.tools.filePicker.model.FileScanActEvent;
import com.chookss.tools.filePicker.model.FileScanFragEvent;
import com.chookss.tools.filePicker.model.FileScanSortChangedEvent;
import com.chookss.tools.filePicker.util.FileSizeUtil;
import com.chookss.tools.filePicker.util.FileUtils;
import com.google.android.material.snackbar.Snackbar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * FileTypeListFragment
 */
public class FileTypeListFragment extends BaseFileFragment implements
        EssMimeTypeCollection.EssMimeTypeCallbacks {

    private static final String ARG_FileType = "ARG_FileType";
    private static final String ARG_IsSingle = "mIsSingle";
    private static final String ARG_MaxCount = "mMaxCount";
    private static final String ARG_SortType = "mSortType";
    private static final String ARG_Loader_Id = "ARG_Loader_Id";

    private String mFileType;
    private boolean mIsSingle;
    private int mMaxCount;
    private int mSortType;
    private int mLoaderId;

    private boolean mSortTypeHasChanged = false;

    private List<EssFile> mSelectedFileList = new ArrayList<>();

    private RecyclerView mRecyclerView;
    private FileListAdapter mAdapter;
    private EssMimeTypeCollection mMimeTypeCollection = new EssMimeTypeCollection();

    public FileTypeListFragment() {
    }

    public static FileTypeListFragment newInstance(String param1, boolean IsSingle, int mMaxCount, int mSortType, int loaderId) {
        FileTypeListFragment fragment = new FileTypeListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_FileType, param1);
        args.putBoolean(ARG_IsSingle, IsSingle);
        args.putInt(ARG_MaxCount, mMaxCount);
        args.putInt(ARG_SortType, mSortType);
        args.putInt(ARG_Loader_Id, loaderId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mFileType = getArguments().getString(ARG_FileType);
            mIsSingle = getArguments().getBoolean(ARG_IsSingle);
            mMaxCount = getArguments().getInt(ARG_MaxCount);
            mSortType = getArguments().getInt(ARG_SortType);
            mLoaderId = getArguments().getInt(ARG_Loader_Id);
        }
    }

    @Override
    public int getFragmentLayout() {
        return R.layout.fragment_file_type_list;
    }

    @Override
    protected void lazyLoad() {
        mMimeTypeCollection.load(mFileType, mSortType, mLoaderId);
    }

    @Override
    protected void initUI(View view) {
        mMimeTypeCollection.onCreate((FragmentActivity) getActivity(), this);
        EventBus.getDefault().register(this);
        mRecyclerView = view.findViewById(R.id.rcv_file_list_scan);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new FileListAdapter(new ArrayList<EssFile>(), getActivity());
        mRecyclerView.setAdapter(mAdapter);
//        mAdapter.bindToRecyclerView(mRecyclerView);
        mAdapter.setEmptyView(R.layout.loading_layout);
        super.initUI(view);
    }

    /**
     * 接收到Activity刷新最大数量后
     *
     * @param event event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFreshCount(FileScanActEvent event) {
        mMaxCount = event.getCanSelectMaxCount();
    }

    /**
     * 接收到Activity改变排序方式后
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFreshSortType(FileScanSortChangedEvent event) {
        mSortType = event.getSortType();
        if (mLoaderId == event.getCurrentItem() + EssMimeTypeCollection.LOADER_ID) {
            mMimeTypeCollection.load(mFileType, mSortType, mLoaderId);
        } else {
            mSortTypeHasChanged = true;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            if (!isFirstLoad && mSortTypeHasChanged) {
                mSortTypeHasChanged = false;
                mAdapter.setNewData(new ArrayList<EssFile>());
                mAdapter.setEmptyView(R.layout.loading_layout);
                mMimeTypeCollection.load(mFileType, mSortType, mLoaderId);
            }
        }
    }

    /**
     * 查找文件位置
     */
    private int findFileIndex(EssFile item) {
        for (int i = 0; i < mSelectedFileList.size(); i++) {
            if (mSelectedFileList.get(i).getAbsolutePath().equals(item.getAbsolutePath())) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mMimeTypeCollection != null) {
            mMimeTypeCollection.onDestroy();
        }

    }

    @Override
    public void onFileLoad(List<EssFile> essFileList) {
        Log.i("TAG", "size --> " + essFileList.size());
        mAdapter.setNewData(essFileList);
        mRecyclerView.scrollToPosition(0);
        if (essFileList.isEmpty()) {
            mAdapter.setEmptyView(R.layout.empty_file_list);
        }
    }

    @Override
    public void onFileReset() {

    }
    class FileListAdapter extends BaseQuickAdapter<EssFile, BaseViewHolderEx> {

//        private FileListAdapter.onLoadFileCountListener loadFileCountListener;
        private Context mContext;

//        public interface onLoadFileCountListener {
//            void onLoadFileCount(int posistion);
//        }
//
//        public FileListAdapter.onLoadFileCountListener getLoadFileCountListener() {
//            return loadFileCountListener;
//        }
//
//        public void setLoadFileCountListener(FileListAdapter.onLoadFileCountListener loadFileCountListener) {
//            this.loadFileCountListener = loadFileCountListener;
//        }

        public FileListAdapter(@Nullable List<EssFile> data, Context mContext) {
            super(R.layout.item_file_list, data);
            this.mContext = mContext;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, EssFile item) {
            TextView textView = helper.getView(R.id.tv_item_file_list_desc);
            ImageView ivStatus = helper.getView(R.id.ivStatus);
            RelativeLayout rlStatus = helper.getView(R.id.rlStatus);
//        if (item.isDirectory()) {
//            helper.setVisible(R.id.iv_item_file_select_right, true);
//            if(item.getChildFolderCount().equals("加载中")){
//                //查找数量
//                if(loadFileCountListener!=null){
//                    loadFileCountListener.onLoadFileCount(helper.getAdapterPosition());
//                }
//            }
//            textView.setText(String.format(mContext.getString(R.string.folder_desc), item.getChildFileCount(),item.getChildFolderCount()));
//        } else {
            textView.setText(String.format(mContext.getString(R.string.file_desc), FileUtils.getDateTime(item.getAbsolutePath()), FileSizeUtil.getAutoFileOrFilesSize(item.getFile())));
//        }
            helper.setText(R.id.tv_item_file_list, item.getName());
            RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) ivStatus.getLayoutParams();

            if (item.isChecked()) {
                params.height= Utils.dip2px(mContext,24);
                params.width= Utils.dip2px(mContext,24);
                ivStatus.setBackgroundResource(R.drawable.icon_fx_select);
            } else {
                params.height= Utils.dip2px(mContext,14);
                params.width= Utils.dip2px(mContext,14);
                ivStatus.setBackgroundResource(R.drawable.shape_circle_dddddd_10);
            }
            ivStatus.setLayoutParams(params);
            ImageView imageView = helper.getView(R.id.iv_item_file_select_left);
            String fileNameExtension = FileUtils.getExtension(item.getName()).toLowerCase();
            switch (fileNameExtension) {
                case "doc":
                case "docx":
                    imageView.setImageResource(R.drawable.icon_w_80);
                    break;
                case "pdf":
                    imageView.setImageResource(R.drawable.icon_pdf_80);
                    break;
                case "ppt":
                case "pptx":
                    imageView.setImageResource(R.drawable.icon_p_80);
                    break;
                case "xls":
                case "xlsx":
                    imageView.setImageResource(R.drawable.icon_x_80);
                    break;
                case "ext":
                default:
                    if (item.isDirectory()) {
                        imageView.setImageResource(R.drawable.icon_mr_80);
                    } else {
                        imageView.setImageResource(R.drawable.icon_mr_80);
                    }
                    break;
            }
//            helper.itemView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (Urls.antiShake.check()) {
//                        return;
//                    }
//                    if(!MyApp.mIsInitTBSSuccess){
//                        //腾讯文件浏览功能失败
//                        FileOpen.openFile(mContext,item.getAbsolutePath());
//                    } else if(!MyApp.docunmentOpen){
//                        Intent intent=new Intent(mContext, DocumentLocalPreviewActivity.class);
//                        intent.putExtra("fileUrl",item.getAbsolutePath());
//                        intent.putExtra("fileName",item.getName());
//                        mContext.startActivity(intent);
//                    }
//
//                }
//            });
            rlStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //选中某文件后，判断是否单选
//                    if (mIsSingle) {
//                        mSelectedFileList.add(item);
//                        EventBus.getDefault().post(new FileScanFragEvent(item, true));
//                        return;
//                    }
                    if (mAdapter.getData().get(helper.getItemPosition()).isChecked()) {
                        int index = findFileIndex(item);
                        if (index != -1) {
                            mSelectedFileList.remove(index);
                            EventBus.getDefault().post(new FileScanFragEvent(item, false));
                            mAdapter.getData().get(helper.getItemPosition()).setChecked(!mAdapter.getData().get(helper.getItemPosition()).isChecked());
                            mAdapter.notifyItemChanged(helper.getItemPosition());
                        }
                    } else {
                        if (mMaxCount <= 0) {
                            //超出最大可选择数量后
                            Snackbar.make(mRecyclerView, "您最多只能选择" + SelectOptions.getInstance().maxCount + "个。", Snackbar.LENGTH_SHORT).show();
                            return;
                        }
                        mSelectedFileList.add(item);
                        EventBus.getDefault().post(new FileScanFragEvent(item, true));
                        mAdapter.getData().get(helper.getItemPosition()).setChecked(!mAdapter.getData().get(helper.getItemPosition()).isChecked());
                        mAdapter.notifyItemChanged(helper.getItemPosition());
                    }
                }
            });
        }
    }

}
